﻿using System;
using System.Collections.Generic;
using Common;

namespace Net
{
    public class NetWorkManager : Singleton<NetWorkManager>
    {
        private WebSocketClient m_Client;
        
        private List<BaseMessage> m_MessageQueue = new List<BaseMessage>();

        public NetWorkManager()
        {
            m_Client = new WebSocketClient();
        }

        public void StartConnect()
        {
            m_Client.StartConnect();
        }
        
        public void CloseConnect()
        {
            m_Client.CloseConnect();
        }

        public void SendBytesAsync(byte[] data)
        {
            m_Client.SendBytesAsync(data);
        }

        public void SendCmdMessageAsync(BaseMessage message)
        {
            m_Client.SendCmdMessageAsync(message);
        }

        #region HeartBeat

        byte[] m_heartBeatBytes;
        float m_heartBeatTimer;
        const int HeartBeatIntervalSecond = 10;
        private void SendHeartBeat()
        {
            if (m_heartBeatBytes == null)
            {
                var cmd = new cmd();
                cmd.id = MessageDefine.U2LS_UserHeartBeatRequest;
                cmd.data = new U2LS_UserHeartBeatRequest().Serialize();
                m_heartBeatBytes = cmd.Serialize();
            }
            
            SendBytesAsync(m_heartBeatBytes);
        }
        
        private void UpdateHeartBeat()
        {
            if (!m_Client.IsConnected())
            {
                return;
            }
            m_heartBeatTimer += UnityEngine.Time.deltaTime;
            if (m_heartBeatTimer >= HeartBeatIntervalSecond)
            {
                m_heartBeatTimer = 0;
                SendHeartBeat();
            }
        }

        #endregion
        

        
        public void EnqueueMessage(BaseMessage message)
        {
            lock (m_MessageQueue)
            {
                m_MessageQueue.Add(message);
            }
        }
        
        public void Update()
        {
            lock (m_MessageQueue)
            {
                if (m_MessageQueue.Count > 0)
                {
                    foreach (var message in m_MessageQueue)
                    {
                        try
                        {
                            MessageDispatcher.Dispatch(message);
                        }
                        catch (Exception e)
                        {
#if UNITY_EDITOR
                            UnityEngine.Debug.LogError($"Error in Dispatch message: {message.MsgId}" + e);
#endif
                        }
                    }
                    m_MessageQueue.Clear();
                }
            }
            UpdateHeartBeat();
        }
        
        

    }
}